﻿using Microsoft.Extensions.DependencyInjection;
using System;

namespace Fast
{
    public abstract class FastApplicationBase : IFastApplicationBase
    {
        public IServiceProvider ServiceProvider { get; private set; }

        public IServiceCollection Services { get; }

        internal FastApplicationBase(IServiceCollection services)
        {
            Check.NotNull(services, nameof(services));

            InternalApp.Services = services;

            Services = services;

            Services.AddSingleton<IFastApplicationBase>(this);

            AddCoreService();
        }

        public virtual void Shutdown()
        {
        }

        public virtual void Dispose()
        {
        }


        /// <summary>
        /// 初始化 <see cref="Startup.Configure"/>
        /// </summary>
        protected virtual void InitializeStartups()
        {
            using (var scope = ServiceProvider.CreateScope())
            {
                scope.ServiceProvider
                    .GetRequiredService<IStartupManager>()
                    .Configure(new ConfigureContext(scope.ServiceProvider));
            }
        }

        /// <summary>
        /// 设置 <see cref="IServiceProvider"/>
        /// </summary>
        /// <param name="serviceProvider"></param>
        protected virtual void SetServiceProvider(IServiceProvider serviceProvider)
        {
            ServiceProvider = serviceProvider;
        }

        /// <summary>
        /// 添加核心服务
        /// </summary>
        private void AddCoreService()
        {
            Services.AddDependencyInjection();

            Services.AddFastJsonSerializer();

            Services.AddStartups();
        }
    }
}